package com.zbdx.controller;

import com.zbdx.dao.CarDao;
import com.zbdx.dao.impl.CarDaoImpl;
import com.zbdx.domain.User;
import com.zbdx.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author ghp
 * @Creat 2024/9/19 17:57
 * @Version 1.0
 * Description:
 */
@WebServlet("/shopping/car/removeGoods")
public class removeServlet extends HttpServlet {
    private CarDao carDao = new CarDaoImpl();
    private QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids[]");
        System.out.println("ids[] = " + ids);
        if (ids != null) {
            List<Integer> idList = Arrays.stream(ids).map(Integer::parseInt).collect(Collectors.toList());
            HttpSession session = req.getSession();
            String username = (String) session.getAttribute("user");
            String sql="SELECT * FROM users2 WHERE username=?";
            User user = null;
            try {
                user = qr.query(sql, new BeanHandler<User>(User.class), username);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

            int userId = user.getId();
            boolean flag = false;
            try {
                flag = carDao.removeProduct(idList, userId);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

            if(flag) resp.getWriter().print(1);
            else resp.getWriter().print(0);
        } else {
            resp.getWriter().print(0);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
